Providing a Custom Editor for a Property

Type editors provide a convenient way of telling the property grid how to display a type whenever and wherever it occurs, but sometimes more fine-grained control is required. For example, in the Person class, the Height property is displayed in centimeters. It might be useful to allow users to enter the height using feet and inches. But a type editor for integers would also encompass the Age property, and it would be extremely confusing for users to enter ages using feet and inches!

What is required here is a property editor. A property editor tells the grid to use a custom editing template for a specific property of the nominated type only. Other properties are unaffected and continue to use the default editor (unless of course they too are assigned a property editor).

Defining the Editing Template

As with type editors, the essence of a property editor is a data template. The only difference is in the way you set up the data bindings in the template. The value being edited is accessed using the special path “Value”. The reason for this is that the purpose of a type editor is to edit instances of class types, which can be done through their properties; but a property editor has to edit values of immutable types such as integers or strings. Conversely, it is undesirable to have a property editor template bind to a specific property such as Height, because then it would be impossible to reuse the template to allow, say, a Distance property to be edited using the same template. So the editor template looks like this:

CopyFeet and inches editor
<DataTemplate x:Key='FeetAndInchesEditor'>
    <ms:TextBox BorderThickness='0' Text='{Binding Value, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource FeetAndInchesConverter}}'/>
  </DataTemplate>

Note the Value path in the TextBox binding.

Telling the Property Grid to Use the New Template

We now need to tell the PropertyGrid control to use this template for the Height property of the Person type. To do this, add a PropertyEditor object to the PropertyGrid.Editors collection. In the example, this fits in after the type editor added in the previous step:

CopyTelling the property grid to use custom editors
<ms:PropertyGrid.Editors>
        <ms:TypeEditor EditedType='{x:Type t:PhoneNumber}' EditorTemplate='{StaticResource PhoneNumberEditor}'/>
        <ms:PropertyEditor PropertyName='Height' DeclaringType='{x:Type t:Person}' EditorTemplate='{StaticResource FeetAndInchesEditor}'/>
      </ms:PropertyGrid.Editors>

When deciding which editor to use for a property, the PropertyGrid control uses the first entry in the list that matches. So if you define a type editor for a custom type, and want to override it for a specific property of that type, the property editor must appear before the type editor in the list.
 

See 04_ProvidingACustomEditorForAProperty.xaml in the PropertyGridCustomization project.

Next step: Styling Built-In Editors